package com.aloudmeta.grpc.client;

import com.aloudmeta.grpc.demo.DubboEchoServiceGrpc;
import com.aloudmeta.grpc.demo.EchoRequest;
import com.aloudmeta.grpc.demo.EchoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;

/**
 * huaixin 2022/1/21 5:10 PM
 */
@RestController
@Slf4j
@RequestMapping("grpc")
public class DubboRpcProxyController {

    @DubboReference(version = "1.0.0", check = false)
    private DubboEchoServiceGrpc.IEchoService echoService;

    @RequestMapping("/hello")
    public String hello(@RequestParam("name") String name) {
        try {
            log.info("yyyyy hRpcProxyController.hello:{}", name);
            RpcContext.getContext().set("teantid", "xxx");

            EchoRequest request = EchoRequest.newBuilder().setMessage(name).build();
            Iterator<EchoResponse> iterator = echoService.echo(request);
            while (iterator.hasNext()) {
                System.out.println(iterator.next().getMessage());
            }
            return "success";
        } catch (Exception e) {
            log.error(e.getCause().getMessage(), e.getCause());
            return e.getCause().getMessage();
        }
    }
}
